﻿/* Copyright SysMates Technologies Pte. Ltd. */
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text.RegularExpressions;
using AppPressFramework;
using System.Globalization;
using System.Resources;
using System.IO;
using AppPressFramework;
using ApplicationClasses;

namespace Application
{
    public partial class AppLogic
    {
        #region Menu Events
        public static void OnClick(AppPress a, AppPressDemoMenusExtensionClass.ControlsFieldClass Controls)
        {
            ControlsClass.Redirect(a, null, null);
        }
        public static void OnClick(AppPress a, AppPressDemoMenusExtensionClass.ValidationsFieldClass ControlValidations)
        {
            ControlValidationsClass.Redirect(a, null, null);
        }
        public static void OnClick(AppPress a, AppPressDemoMenusExtensionClass.ActionsFieldClass ControlEvents)
        {
            AppPressControlEventsClass.Redirect(a, null, null);
        }
        public static void OnClick(AppPress a, AppPressDemoMenusExtensionClass.PropertiesFieldClass FormContainers)
        {
            AppPressFormContainerGridsClass.Redirect(a, null, null);
        }
        public static void OnClick(AppPress a, AppPressDemoMenusExtensionClass.AutoRefreshFieldClass Examples)
        {
            ExamplesClass.Redirect(a, null, null);
        }
        public static void OnClick(AppPress a, AppPressDemoMenusExtensionClass.UserControlsFieldClass Examples)
        {
            UserDefinedControlsClass.Redirect(a, null, null);
        }
        #endregion

        #region Controls
        public static void Init(AppPress a, ControlsClass AppPressControls)
        {
            AppPressControls.DateTime.MinDate = DateTime.Now.Date;
        }
        #endregion

        #region Control Events
        public static string Options(AppPress a, ControlsClass.PickoneFieldClass Pickone)
        {
            string qry = "Select Id, Name From AppPressDemo_Countries";
            return qry;
        }
        public static string Options(AppPress a, ControlsClass.PickoneRadioStyleFieldClass Pickone)
        {
            string qry = "Select Id, Name From AppPressDemo_Countries";
            return qry;
        }
        public static string Options(AppPress a, ControlsClass.PickoneAutoCompleteFieldClass Pickone)
        {
            string qry = "Select Id, Name From AppPressDemo_Countries";
            return qry;
        }
        public static string Options(AppPress a, ControlsClass.PickMultipleFieldClass PickMultiple)
        {
            string qry = "Select Id, Name From AppPressDemo_Countries";
            return qry;
        }
        public static string Options(AppPress a, ControlsClass.EmployeeStatusFieldClass EmployeeStatus)
        {
            string qry = "Select * From AppPressDemo_EmployeeStatus";
            return qry;
        }
        public static string Options(AppPress a, ControlsClass.PickMultiplePopupFieldClass PickMultiple)
        {
            string qry = "Select Id, Name From AppPressDemo_Countries";
            return qry;
        }
        public static string Options(AppPress a, AppPressControlEventsClass.OnChangePickoneFieldClass OnChangePickone)
        {
            return null;//???
        }
        public static void OnClick(AppPress a, ControlsClass.SubmitFieldClass Submit)
        {
            Submit.FormData.Validate();
            a.AlertMessage("Page validated.");
        }
        public static void OnClick(AppPress a, ControlsClass.SubmitLinkFieldClass Submit)
        {
            Submit.FormData.Validate();
            a.AlertMessage("Page validated.");
        }
        public static void Calc(AppPress a, ControlsClass.FileUploadPreviewFieldClass Preview)
        {
            var demoControls = Preview.FormData;
            var imageUrl = "";
            if (!demoControls.FileUpload.val.IsNullOrEmpty())
                imageUrl = a.GetFileUploadImageUrl(Convert.ToInt32(demoControls.FileUpload.val), 100);
            Preview.val = "<img src='" + imageUrl + "'/> ";
        }

        public static string Options(AppPress a, ControlsClass.FormContainerGridWithPopupPopupClass.CountryFieldClass Country)
        {
            string qry = "Select Id, Name From AppPressDemo_Countries";
            return qry;
        }
        public static string Options(AppPress a, ControlsClass.FormContainerGridWithPopupPopupClass.StateFieldClass State)
        {
            var countryId = State.FormData.Country.val;
            if (countryId.IsNullOrEmpty())
                countryId = "-1";
            string qry = "Select Id, Name From AppPressDemo_States Where CountryId = " + countryId;
            return qry;
        }
        public static string Options(AppPress a, ControlsClass.FormContainerGridWithPopupPopupClass.CityFieldClass City)
        {
            var StateId = City.FormData.State.val;
            if (StateId.IsNullOrEmpty())
                StateId = "-1";
            string qry = "Select Id, Name From AppPressDemo_Cities Where StateId = " + StateId;
            return qry;
        }

        public static string Options(AppPress a, ControlsClass.FormContainerGridInlineRowClass.StateFieldClass State)
        {
            var countryId = State.FormData.Country.val;
            if (countryId.IsNullOrEmpty())
                countryId = "-1";
            string qry = "Select Id, Name From AppPressDemo_States Where CountryId = " + countryId + " Or Id = '" + State.val + "'";
            return qry;
        }
        public static string Options(AppPress a, ControlsClass.FormContainerGridInlineRowClass.CityFieldClass City)
        {
            var StateId = City.FormData.State.val;
            if (StateId.IsNullOrEmpty())
                StateId = "-1";
            string qry = "Select Id, Name From AppPressDemo_Cities Where StateId = " + StateId + " Or Id = '" + City.val + "'";
            return qry;
        }

        public static List<FormData> Domain(AppPress a, ControlsClass.FormContainerDynamicFieldClass FormContainerDynamic)
        {
            switch (FormContainerDynamic.FormData.EmployeeStatus.val)
            {
                case null:
                    return null;
                case "1":
                    return FormContainerDynamic.BindSingleForm(a, "Joined");
                default:
                    return FormContainerDynamic.BindSingleForm(a, "Resigned");
            }
        }
        #endregion

        #region Validations
        public static void OnClick(AppPress a, ControlValidationsClass.SubmitFieldClass Submit)
        {
            Submit.FormData.Validate();
            a.AlertMessage("Validated successfully.");
        }
        #endregion

        #region FormContainerGrid

        #endregion

        #region FormContainerSingleFormMultipleTypes
        public static string Options(AppPress a, AppPressFormContainerGridsClass.EmployeeStatusFieldClass EmployeeStatus)
        {
            return "Select * From AppPressDemo_EmployeeStatus";
        }
        public static List<FormData> Domain(AppPress a, AppPressFormContainerGridsClass.DependentFormFieldClass DependentForms)
        {
            switch (DependentForms.FormData.EmployeeStatus.val)
            {
                case null:
                    return null;
                case "1":
                    return DependentForms.BindSingleForm(a, "Joined");
                default:
                    return DependentForms.BindSingleForm(a, "Resigned");
            }
        }
        public static void OnClick(AppPress a, AppPressFormContainerGridsClass.SaveFieldClass Save)
        {
            Save.FormData.SaveAndUpdateUI(a);
        }

        public static string Domain(AppPress a, AppPressFormContainerGridsClass.ClientAccountsFieldClass ClientAccounts)
        {
            var search = ClientAccounts.FormData.Search.val;
            var searchClause = search == null ? "" : @" and Name like '%" + search.ToSqlEncodedString() + "%' or Phone like '%" + search.ToSqlEncodedString() + "%' or Email like '%" + search.ToSqlEncodedString() + @"%'";
            var query = @" 
                Select
                    AppPressDemo_ClientAccounts.*
                From 
                    AppPressDemo_ClientAccounts 
                Where 1=1 " + searchClause + @"
                Order by Id Asc";
            return query;
        }
        #endregion

        #region Examples
        public static void OnClick(AppPress a, ExamplesClass.LoadFileFieldClass LoadFile)
        {
            //List<string> s = new List<string>();
            //s.Add("HelloTest-1");
            //s.Add("HelloTest-2");
            //s.Add("HelloTest-3");
            //s.Add("HelloTest-4");
            //a.DownloadExcel("EXECUTE TestReport", "Hello", s);
            //return;

            var formData = LoadFile.FormData;
            //Validate all controls first.
            formData.Validate();

            var filePath = a.GetFileUploadAsTempFilePath(Convert.ToInt32(formData.FileUpload.val));//If file saved in DB then retrive it from Database.
            StreamReader sr = new StreamReader(filePath);
            string line = "";
            int totalLines = 0;
            while ((line = sr.ReadLine()) != null)
            {
                totalLines = totalLines + 1;
            }
            sr.Close();
            a.AlertMessage("File " + Path.GetFileName(filePath) + " uploaded successfully with total " + totalLines + " lines.");
        }
        public static List<FormData> Domain(AppPress a, ExamplesClass.EncryptionFieldClass Encryption)
        {
            return Encryption.BindSingleForm(a, "Encryption");
        }
        public static void OnClick(AppPress a, EncryptionClass.SaveFieldClass Save)
        {
            Save.FormData.SaveAndUpdateUI(a);
        }
        public static void OnClick(AppPress a, EncryptionClass.DownloadFieldClass Download)
        {
            a.DownloadFile(long.Parse(Download.FormData.DESFile.val));
        }
        #endregion
        public static void Init(AppPress a, RemoteFormsClass RemoteForms)
        {
            RemoteForms.Instance.val = "XXX";
        }
        public static void OnClick(AppPress a, AppPressDemoMenusExtensionClass.RemoteFormsFieldClass RemoteForms)
        {
            RemoteFormsClass.Redirect(a, null, null);
        }
        public static void OnClick(AppPress a, AppPressDemoMenusExtensionClass.VisualizationFieldClass Visualization)
        {
            VisualizationClass.Redirect(a, null, null);
        }

        private static string GetJSONFromQuery(AppPress a, string query)
        {
            var dr = a.ExecuteQuery(query);
            var result = "";
            try
            {
                var data = new List<List<string>>();
                while (dr.Read())
                {
                    result += "[";
                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        result += dr[i].ToString() + ",";
                    }
                    result += "],";
                }
                return result;
            }
            finally
            {
                dr.Close();
            }
        }

        public static string Domain(AppPress a, VisualizationClass.GraphsFieldClass Graphs)
        {
            return @"
                Select 'G1' GraphId 
                UNION 
                Select 'G2' GraphId";
        }
        public static void Init(AppPress a, VisualizationClass Visualization)
        {
            a.JsStr.Append(@"google.setOnLoadCallback(drawChart);
                // Callback that creates and populates a data table,
                // instantiates the pie chart, passes in the data and
                // draws it.
                googleChartStack = [];

                function drawChart() {
                    for (var i = googleChartStack.length - 1; i >= 0; i--) {
                        googleChartStack[i]();
                    }
                }");
        }
        public static void Calc(AppPress a, VisualizationClass.GraphsFieldClass Graphs)
        {
            foreach (var GraphsRow in Graphs.val)
            {
                var graphId = GraphsRow.GraphId.val;
                var json = GetJSONFromQuery(a, "Select 2014 as Year, 1000 Sales, 400 Expenses, 200 Profit");
                a.JsStr.Append(@"  googleChartStack.push(
    
              function draw" + graphId + @"() {
                var data = new google.visualization.DataTable();
                data.addColumn('number', 'Year');
                data.addColumn('number', 'Sales');
                data.addColumn('number', 'Expenses');
                data.addColumn('number', 'Profit');
                data.addRows([" + json + @"]);

                var options = {
                  chart: {
                    title: 'Company Performance',
                    subtitle: 'Sales, Expenses, and Profit: 2014-2017',
                    }
                  }

                var chart = new google.charts.Bar(document.getElementById('" + GraphsRow.Graph.GetHtmlId() + @"'));

                chart.draw(data, options);
                // Add our selection handler.
                google.visualization.events.addListener(chart, 'select', function () {
                  var selection = chart.getSelection();
                  var message = '';
                  for (var i = 0; i < selection.length; i++) {
                    message += selection[i].column;
                  }
                  if (message != '') {
                    debugger;
                    " + GraphsRow.SelectedColumn.GetSetValueJSScript("message") + @"
                    " + GraphsRow.Details.GetOnClickJSScript() + @"
                    }
                });
            });"
                           );
            }
        }

        public static void OnClick(AppPress a, VisualizationClass.GraphsRowClass.DetailsFieldClass Details)
        {
            a.AlertMessage("Column Clicked: " + Details.FormData.SelectedColumn.val);
        }
        public static string Domain(AppPress a, RemoteFormsClass.NotificationsFieldClass Notifications)
        {
            return "Select * From AppPressDemo_RemoteForms";
        }

        public static void OnClick(AppPress a, RemoteFormsClass.NotificationsRowClass.OpenPopupFieldClass OpenPopup)
        {
            a.RemotePopup(int.Parse(OpenPopup.FormData.id), "RemoteFormsPopup", OpenPopup.FormData.id, null);
        }
        public static void OnClick(AppPress a, RemoteFormsClass.RemoteRedirectFieldClass RemoteRedirect)
        {
            a.RemoteRedirect(2, "RemoteForms", null, null);
        }

        public static void OnClick(AppPress a, RemoteFormsPopupClass.SaveFieldClass Save)
        {
            Save.FormData.Save(a);
            Save.FormData.RefreshContainer(a);
            a.CommitTrans();
            a.ClosePopup();
        }
    }
}